package com.ai.networking.netty.handler;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


/**
 * @Author jiaok
 * @Date 2023-06-16 16:09
 */
@Slf4j
public class HearBeatHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读操作的超时次数
     */
    volatile private int readIdleTimes = 0;
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    
        //获取该通道的ip
        String ip = ctx.channel().remoteAddress().toString();
        int clientPort = Integer.parseInt(ip.split(":")[1]);
        if (clientPort == 18005){
            //判断evt的事件类型,是否为心跳抛出的读、写、读写空闲
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()) {
                case READER_IDLE:
                    readIdleTimes++;
                    log.info("============  {} 读超时...  ============",ip);
                    break;
                case WRITER_IDLE:
                    readIdleTimes++;
                    log.info("============  {} 写超时...  ============",ip);
                    break;
                case ALL_IDLE:
                    readIdleTimes++;
                    log.info("============  {} 读写超时...  ============",ip);
                    break;
            }
            //如果超时次数大于5次，则关闭客户端的连接
            if (readIdleTimes > 5) {
                log.info("============  {} 超时超过五次，关闭连接...  ============",ip);
                ctx.channel().close();
            }   
        }
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        readIdleTimes = 0;
        ctx.fireChannelRead(msg); // 继续传播事件
    }
}
